import json
from machine import Pin
import time
from wifi_manager import WiFiManager
from web_file_manager import WebFileManager
import ulogger


def get_loggers(config: dict):
    class RealClock(ulogger.BaseClock):
        def __call__(self) -> str:
            timestamp = time.mktime(time.localtime())
            timestamp += 8 * 3600 # 加上 8 小时（北京时间）
            local_time = time.localtime(timestamp)
            return f'{local_time[0]:04d}-{local_time[1]:02d}-{local_time[2]:02d} {local_time[3]:02d}:{local_time[4]:02d}:{local_time[5]:02d}'
    clock  = RealClock()

    handlers = []

    if config['log']['terminal']['enable']:
        handlers.append(ulogger.Handler(
            level=ulogger.INFO,
            colorful=True,
            fmt="[&(level)%][&(time)%][&(name)%] &(msg)%",
            clock=clock,
            direction=ulogger.TO_TERM,
        ))

    if config['log']['udp']['enable']:
        handlers.append(ulogger.Handler(
            level=ulogger.INFO,
            fmt="[&(level)%][&(time)%][&(name)%] &(msg)%",
            clock=clock,
            direction=ulogger.TO_UDP,
            udp_target=(config['log']['udp']['target_ip'], config['log']['udp']['target_port'])
        ))


    return (ulogger.Logger('main', handlers), ulogger.Logger('wifi', handlers), ulogger.Logger('webfile', handlers))



def main():
    try:
        with open('config.json') as f:
            config = json.load(f)

        main_logger, wifi_logger, webfile_logger = get_loggers(config)
        main_logger.info("<<< Night Lamp Project >>> Starting...")

        wifi_manager = WiFiManager(
            config['wifi']['ssid'], config['wifi']['password'], 
            as_hostname=config['wifi']['as_hostname'],
            state_led_pin_no=config['wifi']['state_led_pin_no'], 
            logger=wifi_logger)
        wifi_manager.enable()

        web_file_manager = WebFileManager(logger = webfile_logger)
        web_file_manager.start_file_server()

        infrared_pin = Pin(config['sensors']['infrared']['pin_no'], Pin.IN, Pin.PULL_DOWN)
        main_logger.info(f'Infrared pin no: {config['sensors']['infrared']['pin_no']}')

        while True:
            if infrared_pin.value() == 1:
                main_logger.info()
                main_logger.info('Infrared high level detected, waiting for low level...')
                start_time = time.ticks_ms() / 1000

                while infrared_pin.value() == 1:
                    pass

                end_time = time.ticks_ms() / 1000
                main_logger.info(f'High level stands for {end_time - start_time:.2f} seconds')
    except KeyboardInterrupt:
        main_logger.info("KeyboardInterrupt")
        web_file_manager.stop_file_server()
        wifi_manager.disable()
    
if __name__ == '__main__':
    main()